<template>
    <view>
        <van-config-provider :theme="appStore.theme" :theme-vars="themeVars">
            <view class="absolute right-5 top-5" @click="appStore.change()">
                <van-image :src="appStore.icon" width="35" position="right"/>
            </view>
            <view class="py-5 text-center">
                <van-image width="60" src="/static/logo.png"/>
                <view class="light text-4xl mt-2">周易量化</view>
                <view class="mt-4 text-sm text-title2">{{
                        appStore.data.other.subTitle || ''
                    }}
                </view>
            </view>
            <view>
                <van-tabs v-model:active="appStore.tab" :animated="true">
                    <block v-for="(item, index) in fieldsMap" :key="index">
                        <van-tab :title="!index ? '数据统计' : '当前持仓'">
                            <van-grid :column-num="3" v-for="(a, b) in item" :key="b">
                                <van-grid-item v-for="(c, d) in a" :key="d">
                                    <view class="light text-sm font-bold">{{ c }}</view>
                                    <view class="light text-sm pt-3.5">{{ appStore.data.other[d] }}</view>
                                </van-grid-item>
                            </van-grid>
                        </van-tab>
                    </block>
                    <van-tab title="运行日志">
                        <van-cell-group v-if="appStore.data.list.length">
                            <block v-for="(v, i) in appStore.data.list" :key="i">
                                <van-cell :border="false" :title-class="i ? '' : 'text-red mt-2.5'" :title="v"/>
                            </block>
                        </van-cell-group>
                        <van-empty v-else class="mt-2.5" description="暂无数据"/>
                    </van-tab>
                    <van-tab title="基础配置">
                        <van-form @submit="onSubmit">
                            <van-cell-group class="pt-2.5">
                                <van-field name="switch" label="量化开关" center>
                                    <template #input>
                                        <van-switch v-model="appStore.formData.status"/>
                                    </template>
                                </van-field>
                                <van-field v-model="appStore.formData.subTitle" type="text" name="二级标题"
                                           label="二级标题"
                                           placeholder="二级标题" center/>
                                <van-field name="radio" label="补仓策略" center>
                                    <template #input>
                                        <van-radio-group v-model="appStore.formData.tactics" direction="horizontal">
                                            <van-radio name="1">倍投</van-radio>
                                            <van-radio name="2">等额</van-radio>
                                        </van-radio-group>
                                    </template>
                                </van-field>
                                <van-row>
                                    <van-col span="12">
                                        <van-field v-model="appStore.formData.firstOrder" type="number" name="首单数量"
                                                   label="首单数量"
                                                   placeholder="首单数量" center/>
                                    </van-col>
                                    <van-col span="12">
                                        <van-field v-model="appStore.formData.allAddPositionNum" type="digit"
                                                   name="最大补仓次数" label="最大补仓" placeholder="最大补仓次数"
                                                   center/>
                                    </van-col>
                                </van-row>
                                <van-row>
                                    <van-col span="12">
                                        <van-field v-model="appStore.formData.profitRatio" type="number" name="止盈率"
                                                   label="止盈率(%)" placeholder="止盈率" center/>
                                    </van-col>
                                    <van-col span="12">
                                        <van-field v-model="appStore.formData.profitCallbackRatio" type="number"
                                                   name="止盈回调率" label="止盈回调(%)" placeholder="止盈回调率"
                                                   center/>
                                    </van-col>
                                </van-row>
                                <van-row>
                                    <van-col span="12">
                                        <van-field v-model="appStore.formData.stopLossRatio" type="number"
                                                   name="补仓率"
                                                   label="补仓率(%)" placeholder="补仓率" center/>
                                    </van-col>
                                    <van-col span="12">
                                        <van-field v-model="appStore.formData.addPositionCallbackRatio" type="number"
                                                   name="补仓回调率" label="补仓回调(%)" placeholder="补仓回调率"
                                                   center/>
                                    </van-col>
                                </van-row>
                                <van-row>
                                    <van-col span="12">
                                        <van-field v-model="appStore.formData.usdtInit" type="number" name="初始资金"
                                                   label="初始资金" placeholder="初始资金" center/>
                                    </van-col>
                                    <van-col span="12">
                                        <van-field v-model="appStore.formData.password" type="number" name="操作密码"
                                                   label="操作密码" placeholder="操作密码" autocomplete="off" center/>
                                    </van-col>
                                </van-row>
                            </van-cell-group>
                            <div style="margin: 16px;">
                                <van-button plain round block type="success" native-type="submit">提交</van-button>
                            </div>
                        </van-form>
                    </van-tab>
                </van-tabs>
                <view class="text-center text-title2 text-sm fixed bottom-2 right-0 left-0">
                    在线：{{ appStore.data.other.online || '0 人' }}
                </view>
            </view>
        </van-config-provider>
    </view>
</template>
<script setup>
import {
    onUnload
} from '@dcloudio/uni-app';
import {
    reactive,
    ref,
    watch
} from 'vue';
import {
    closeToast,
    showLoadingToast,
    showToast
} from 'vant';
import {
    useAppStore
} from '@/store/modules/app';

// 离开页面，断开连接
onUnload(() => {
    uni.closeSocket();
});

// store数据
const appStore = useAppStore();

// 定制组件样式
const themeVars = reactive({
    cellLineHeight: '10px'
});

// 数据参数映射
const fieldsMap = [
    [{
        usdtInit: '初始资金',
        eq: '当前资金',
        notionalLever: '实际杠杆',
    },
        {
            firstOrder: '首单数量',
            availEq: '可用保证金',
            lever: '杠杆倍数',
        },
        {
            total_profit: '总盈利',
            total_profit_ratio: '总盈利率',
            allAddPositionNum: '最大补仓',
        },
        {
            today_count: '今日做单',
            today_profit: '今日浮盈',
            today_profit_ratio: '今日浮盈率',
        }
    ],
    [{
        avgPx: '开仓均价',
        last: '当前价格',
        liqPx: '爆仓价',
    },
        {
            direction: '开单方向',
            profitRatio: '止盈率',
            profitCallbackRatio: '止盈回调率',
        },
        {
            frozenBal: '占用保证金',
            stopLossRatio: '补仓率',
            addPositionCallbackRatio: '补仓回调率',
        },
        {
            upl: '本单收益',
            uplRatio: '本单收益率',
            addPositionNum: '本单已补仓',
        },
        {
            upBeforeRatio: '反弹前收益率',
            downRate: '当前回调率',
            downBeforeRatio: '回调前收益率',
        }
    ]
];

// 显示加载层
showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0,
});
// 连接websocket
const socketTask = uni.connectSocket({
    url: `${import.meta.env.VITE_APP_BASE_URL || ''}`,
    complete: () => {
    }
});
// 打开webSocket
socketTask.onOpen(function (res) {
    // 发送数据触发服务端推送数据
    socketTask.send({
        data: 'ping',
        fail: () => {
            showToast('打开websocket失败');
        }
    });
});
// webSocket断开事件
socketTask.onClose(function (res) {
    showToast('websocket已断开');
    // 刷新页面重连
    setTimeout(() => {
        window.location.reload();
    }, 1000);
});
// 监听websocket数据推送
socketTask.onMessage(function (res) {
    // 格式化数据
    res = JSON.parse(res.data);
    // 推送数据
    if (res.code == 0) {
        // 获取运行日志
        appStore.data.list = res.data.list;
        // 获取其他数据
        appStore.data.other = res.data.other;
    }
    // 表单反馈
    if (res.code == 1) {
        showToast(res.msg);
    }
});

// 侦听页面数据改变后，刷新表单值、关闭加载层
watch(
    () => appStore.data.other.currencyCoin,
    () => {
        appStore.updateFormData();
        closeToast(true);
    }
);

// 表单提交事件
const onSubmit = () => {
    socketTask.send({
        data: JSON.stringify(appStore.formData)
    });
    // 显示加载层
    showLoadingToast({
        message: '提交中...',
        forbidClick: true,
        duration: 0,
    });
};
</script>
